package exchange

import (
	"github.com/garyburd/redigo/redis"
	"global/libs/structs"
	"sync"
	"time"
	"github.com/parnurzeal/gorequest"
	"github.com/ngaut/log"
	"encoding/json"
	"global/core"
	"strings"
	"global/libs/exchanges"
)

type BitZ struct {
	Slug 			string
	Pool 			*redis.Pool
	Symbols 		[]structs.Symbol
	IntervalC 		*time.Ticker
	mux 			sync.Mutex
	Client 			*gorequest.SuperAgent
}

func NewBitZ(pool *redis.Pool, slug string) InterfaceTicker {
	bitz := &BitZ{
		Pool: 		pool,
		Slug: 		slug,
		IntervalC: 	time.NewTicker(2 * time.Second),
	}

	bitz.Client = gorequest.New()

	return bitz
}

func (t *BitZ) NeedSymbols() bool {
	return false
}

func (t *BitZ) ListenAndAccept() error {
	go func() {
		t.handler()
		for timer := range t.IntervalC.C {
			_ = timer
			go t.handler()
		}
	}()
	return nil
}

func (t *BitZ) handler() {
	start := time.Now()
	_, body, errs := t.Client.
		Get(core.GetBitZUrl("tickerall")).
		Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36").
		End()
	if len(errs) > 0 {
		log.Errorf("Error: %s", errs[0])
		return
	}

	type bitzResponse struct {
		exchanges.BitzBaseResponse
		Data 		map[string]exchanges.BitzTicker 		`json:"data"`
	}

	var bitzResponseData bitzResponse
	err := json.Unmarshal([]byte(body), &bitzResponseData)
	if err != nil {
		log.Errorf("Error: %s", err)
		return
	}

	// 处理数据
	tickers := make([]structs.Ticker, 0)
	for symbol, item := range bitzResponseData.Data {
		coins := strings.Split(symbol, "_")
		var count uint64
		if c, ok := item.DealCount.(uint64); ok {
			count = c
		}

		tickers = append(tickers, structs.Ticker{
			Symbol: 		item.Symbol,
			From:			coins[0],
			To: 			coins[1],
			Volume: 		item.Volume,
			Amount: 		item.QuoteVolume,
			Percent: 		item.PriceChange24h,
			Open: 			item.Open,
			High: 			item.High,
			Low: 			item.Low,
			Close: 			item.Now,
			Number: 		count,
			PriceCny: 			item.Cny,
			PriceUsd: 			item.Usd,
		})
	}

	if err := core.SaveTicker(t.Pool, t.Slug, tickers); err != nil {
		log.Errorf("Error: save ticker failed, msg: %s", err)
		return
	}

	log.Infof("Get all tickers from bit-z complete, take time: %s", time.Since(start))
}
